package bb.lanxing.adapter.mine;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.Intent;
import android.graphics.LinearGradient;
import android.graphics.Shader;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;

import bb.lanxing.util.Log;
import com.alibaba.fastjson.JSON;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.formatter.DefaultAxisValueFormatter;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.github.mikephil.charting.renderer.YAxisRenderer;
import com.github.mikephil.charting.utils.Utils;

import org.apache.commons.cli.HelpFormatter;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;

import bb.lanxing.App;
import bb.lanxing.R;
import bb.lanxing.activity.mine.RankingsOverviewActivity;
import bb.lanxing.activity.sport.HistoryListActivity;
import bb.lanxing.chart.custom.BarXAxisRenderer;
import bb.lanxing.chart.custom.RoundBarChartRenderer;
import bb.lanxing.lib.widget.utils.Density;
import bb.lanxing.manager.SharedManager;
import bb.lanxing.model.database.Medal;
import bb.lanxing.model.database.User;
import bb.lanxing.model.database.Workout;
import bb.lanxing.model.json.MineHotItem;
import bb.lanxing.util.CommonUtil;
import bb.lanxing.util.DateUtil;
import bb.lanxing.util.MedalUtil;
import bb.lanxing.util.ui.DrawableUtils;
import bb.lanxing.util.ui.FlipBitmapDisplayer;
import bb.lanxing.view.FontTextView;
import bb.lanxing.view.sport.SportTypeSwitch;

public class MineInfoPagerAdapter extends PagerAdapter {
	private Double distance;
	private Long duration;
	private MineChartHolder mineChartHolder;
	private MineInfoHolder mineInfoHolder;
	private User user;

	public void setUser(User user) {
		this.user = user;
		if (user == null) {
			Log.i("setUser user is null");
			this.distance = null;
			this.duration = null;
		}
		updatePage(this.mineInfoHolder);
		updatePage(this.mineChartHolder);
		notifyDataSetChanged();
	}

	@NonNull @Override public Object instantiateItem(@NonNull ViewGroup container, int position) {
		if (position == 0) {
			mineInfoHolder = new MineInfoHolder(LayoutInflater.from(container.getContext()).inflate(R.layout.my_profile_page_info, container, false));
			updatePage(mineInfoHolder);
			container.addView(((AbsMineHolder) mineInfoHolder).itemView);
			return mineInfoHolder;
		} else if (position == 1) {
			MineChartHolder mineChartHolder = new MineChartHolder(LayoutInflater.from(container.getContext()).inflate(R.layout.my_profile_page_chart, container, false));
			this.mineChartHolder = mineChartHolder;
			updatePage(mineChartHolder);
			container.addView(((AbsMineHolder) mineChartHolder).itemView);
			return mineChartHolder;
		} else {
			return super.instantiateItem(container, position);
		}
	}

	@Override public void destroyItem(@NonNull ViewGroup viewGroup, int i, @NonNull Object obj) {
		if (obj instanceof AbsMineHolder absMineHolder) {
			absMineHolder.destroy();
			viewGroup.removeView(absMineHolder.itemView);
			if (this.mineInfoHolder == absMineHolder) {
				this.mineInfoHolder = null;
			} else if (this.mineChartHolder != absMineHolder) {
			} else {
				this.mineChartHolder = null;
			}
		}
	}

	@Override public int getCount() {
		return this.user == null ? 1 : 2;
	}

	@Override public boolean isViewFromObject(@NonNull View view, @NonNull Object obj) {
		return (obj instanceof AbsMineHolder) && ((AbsMineHolder) obj).itemView == view;
	}

	private void updatePage(AbsMineHolder absMineHolder) {
		if (absMineHolder == null) {
			return;
		}
		if ((absMineHolder instanceof MineInfoHolder infoHolder)) {
			User user = this.user;
			if (user != null) {
				infoHolder.updateUser(user);
				return;
			}
			infoHolder.setLogout();
			Double d = this.distance;
			if (d == null || this.duration == null) {
				return;
			}
			infoHolder.setLocalDistanceDuration(d, this.duration);
		} else if ((absMineHolder instanceof MineChartHolder chartHolder)) {
			User user2 = this.user;
			if (user2 == null) {
				return;
			}
			chartHolder.setupUserData(user2);
		}
	}

	private static class AbsMineHolder {
		protected Context context;
		private final View itemView;

		protected void destroy() {
		}

		private AbsMineHolder(View view) {
			this.context = view.getContext();
			this.itemView = view;
		}
	}

	private class MineInfoHolder extends AbsMineHolder {
		private TextView tvMonth;
		private ImageView sportTypeIcon;
		private TextView sportTypeBtn;

		private View mLlTotalDistanceLayout;
		private FontTextView totalDistanceView;
		private View mLlRankingLayout;
		private TextView rankingView;
		private TextView monthValidDurationView;

		private int curHotsValue;
		private FlipBitmapDisplayer flipBitmapDisplayer = new FlipBitmapDisplayer(500);
		private ValueAnimator hostAnimator;

		private String medalUrl;

		private MineInfoHolder(View view) {
			super(view);
			bindView(view);

			int month = Calendar.getInstance().get(Calendar.MONTH);
			tvMonth.setText(context.getResources().getStringArray(R.array.month_array)[month]);

			if (App.getContext().isUserSignin()) {
				curHotsValue = App.getContext().getSigninUser().getHotsMonth();
			}

			updateSportType(SharedManager.getInstance().getMineSportType());
		}

		private void bindView(View view) {
			tvMonth = view.findViewById(R.id.tvMonth);
			sportTypeIcon = view.findViewById(R.id.iv_mine_sport_type);
			sportTypeBtn = view.findViewById(R.id.tv_mine_sport_type);
			sportTypeBtn.setOnClickListener(view2 -> onSportTypeClick());

			mLlTotalDistanceLayout = view.findViewById(R.id.llTotalDistanceLayout);
			mLlTotalDistanceLayout.setOnClickListener(v -> onTotalDistanceClick());
			totalDistanceView = view.findViewById(R.id.totalDistanceView);
			mLlRankingLayout = view.findViewById(R.id.llRankingLayout);
			mLlRankingLayout.setOnClickListener(v -> onRankingClick());
			rankingView = view.findViewById(R.id.rankingView);

			monthValidDurationView = view.findViewById(R.id.monthValidDurationView);
		}

		private void onSportTypeClick() {
			SportTypeSwitch sportTypeSwitch = new SportTypeSwitch(this.context, SharedManager.getInstance().getMineSportType(), 3);
			sportTypeSwitch.setOnSportTypeSwitchListener(i -> {
				SharedManager.getInstance().setMineSportType(i);
				MineInfoHolder.this.updateSportType(i);
			});
			sportTypeSwitch.showAsDropDown(this.sportTypeBtn);
		}

		private void onTotalDistanceClick() {
			if (!App.getContext().isUserSignin()) {
				App.getContext().userSignin();
			} else {
				context.startActivity(new Intent(context, HistoryListActivity.class));
			}
		}

		private void onRankingClick() {
			if (!App.getContext().isUserSignin()) {
				App.getContext().userSignin();
			} else {
				SharedManager.getInstance().setRankPeopleType(0);
				context.startActivity(new Intent(context, RankingsOverviewActivity.class));
			}
		}

		private void setLogout() {
			totalDistanceView.setText(HelpFormatter.DEFAULT_LONG_OPT_PREFIX);
			monthValidDurationView.setText("--:--");
			rankingView.setText(HelpFormatter.DEFAULT_LONG_OPT_PREFIX);
			medalUrl = null;
		}

		private void updateUser(User user) {
			playHotValueAnim(user.getHotsMonth(), user.getMedal());
			updateSportType(SharedManager.getInstance().getMineSportType());
		}

		private void setLocalDistanceDuration(double d, long j) {
			totalDistanceView.setText(CommonUtil.getFormatDistance(d));
			monthValidDurationView.setText(DateUtil.format(j * 1000, 4));
		}

		private void playHotValueAnim(int hotsMonth, final Medal medal) {
			int hotsValueOnShow = this.curHotsValue;
			if (hotsMonth == hotsValueOnShow) {
				updateHotValue(hotsMonth, medal);
				return;
			}
			ValueAnimator ofInt = ValueAnimator.ofInt(hotsValueOnShow, hotsMonth);
			this.hostAnimator = ofInt;
			ofInt.addUpdateListener(valueAnimator -> MineInfoHolder.this.updateHotValue((Integer) valueAnimator.getAnimatedValue(), medal));
			this.hostAnimator.addListener(new AnimatorListenerAdapter() {
				@Override public void onAnimationEnd(Animator animator) {
					super.onAnimationEnd(animator);
					MineInfoHolder.this.hostAnimator = null;
				}
			});
			this.hostAnimator.setDuration((long) ((Math.atan(Math.abs(hotsMonth - this.curHotsValue) * 0.1d) * 6000.0d) / 3.141592653589793d));
			this.hostAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
			this.hostAnimator.start();
			this.curHotsValue = hotsMonth;
		}

		public void updateHotValue(int hotValue, Medal medal) {
			if (medal != null) {
				String targetLevelImage = MedalUtil.getTargetLevelImage(hotValue, medal);
				String str = this.medalUrl;
				if (str != null && str.equals(targetLevelImage)) {
					return;
				}
				this.flipBitmapDisplayer.enableAnimation(this.medalUrl != null);
				this.medalUrl = targetLevelImage;
			}
		}

		@Override protected void destroy() {
			super.destroy();
			ValueAnimator valueAnimator = this.hostAnimator;
			if (valueAnimator == null || !valueAnimator.isRunning()) {
				return;
			}
			this.hostAnimator.cancel();
			this.hostAnimator = null;
		}

		public void updateSportType(int i) {
			String string;
			int i2;
			int walkMonthCityRank;
			double walkMonthValidDistance;
			long walkMonthValidDuration;
			if (i == Workout.TYPE_WALKING) {
				string = this.context.getString(R.string.walking);
				i2 = R.drawable.ic_tab_sport_walking_unfocus;
				if (MineInfoPagerAdapter.this.user != null) {
					walkMonthCityRank = MineInfoPagerAdapter.this.user.getWalkMonthCityRank();
					walkMonthValidDistance = MineInfoPagerAdapter.this.user.getWalkMonthValidDistance();
					walkMonthValidDuration = MineInfoPagerAdapter.this.user.getWalkMonthValidDuration();
				} else {
					walkMonthValidDuration = -1;
					walkMonthValidDistance = -1.0d;
					walkMonthCityRank = -1;
				}
			} else if (i != Workout.TYPE_RUNNING) {
				string = this.context.getString(R.string.cycling);
				i2 = R.drawable.ic_tab_sport_cycling_unfocus;
				if (MineInfoPagerAdapter.this.user != null) {
					walkMonthCityRank = MineInfoPagerAdapter.this.user.getCycleMonthCityRank();
					walkMonthValidDistance = MineInfoPagerAdapter.this.user.getCycleMonthValidDistance();
					walkMonthValidDuration = MineInfoPagerAdapter.this.user.getCycleMonthValidDuration();
				} else {
					walkMonthValidDuration = -1;
					walkMonthValidDistance = -1.0d;
					walkMonthCityRank = -1;
				}
			} else {
				string = this.context.getString(R.string.running);
				i2 = R.drawable.ic_tab_sport_running_unfocus;
				if (MineInfoPagerAdapter.this.user != null) {
					walkMonthCityRank = MineInfoPagerAdapter.this.user.getRunMonthCityRank();
					walkMonthValidDistance = MineInfoPagerAdapter.this.user.getRunMonthValidDistance();
					walkMonthValidDuration = MineInfoPagerAdapter.this.user.getRunMonthValidDuration();
				} else {
					walkMonthValidDuration = -1;
					walkMonthValidDistance = -1.0d;
					walkMonthCityRank = -1;
				}
			}
			this.sportTypeBtn.setText(string);
			this.sportTypeIcon.setImageResource(i2);
			DrawableUtils.setTint(this.sportTypeIcon, this.context.getResources().getColor(R.color.c666666));
			if (walkMonthValidDistance != -1.0d) {
				this.totalDistanceView.setText(CommonUtil.getFormatDistance(walkMonthValidDistance));
			}
			if (walkMonthCityRank == -1 || walkMonthValidDistance <= Utils.DOUBLE_EPSILON) {
				this.rankingView.setText(HelpFormatter.DEFAULT_LONG_OPT_PREFIX);
			} else if (walkMonthCityRank > 9999) {
				this.rankingView.setText("9999+");
			} else {
				this.rankingView.setText(String.valueOf(walkMonthCityRank));
			}
			if (walkMonthValidDuration != -1) {
				this.monthValidDurationView.setText(DateUtil.format(walkMonthValidDuration * 1000, 2));//4 original
			}
		}
	}

	private class MineChartHolder extends AbsMineHolder {
		private BarChart mChart;
		private TextView mChartNone;
		private TextView mChartTitle;
		private BarXAxisRenderer xAxisRenderer;

		private void bindView(View view) {
			this.mChart = view.findViewById(R.id.mine_detail_hot_chart);
			this.mChartTitle = view.findViewById(R.id.mine_detail_host_title);
			this.mChartNone = view.findViewById(R.id.mine_detail_host_none);
		}

		private MineChartHolder(View view) {
			super(view);
			bindView(view);
			initChart();
		}

		private void initChart() {
			this.mChart.setDrawBarShadow(false);
			this.mChart.setDrawValueAboveBar(false);
			this.mChart.setPinchZoom(false);
			this.mChart.setDrawGridBackground(false);
			this.mChart.getDescription().setEnabled(false);
			this.mChart.getLegend().setEnabled(false);
			this.mChart.setTouchEnabled(false);
			this.mChart.setScaleXEnabled(false);
			this.mChart.setScaleYEnabled(false);
			this.mChart.setDoubleTapToZoomEnabled(false);
			this.mChart.setDrawMarkers(false);
			BarChart barChart = this.mChart;
			RoundBarChartRenderer roundBarChartRenderer = new RoundBarChartRenderer(barChart, barChart.getAnimator(), this.mChart.getViewPortHandler());
			roundBarChartRenderer.setRoundRadius(2.0f);
			roundBarChartRenderer.getPaintRender().setShader(new LinearGradient(0.0f, Density.dp2px(this.context, 80.0f), 0.0f, 0.0f, -19867, -47803, Shader.TileMode.CLAMP));
			this.mChart.setRenderer(roundBarChartRenderer);
			int color = this.context.getResources().getColor(R.color.grey_999999);
			XAxis xAxis = this.mChart.getXAxis();
			xAxis.setValueFormatter(new DayAxisValueFormatter(this.context));
			xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
			xAxis.setDrawGridLines(false);
			xAxis.setDrawLabels(true);
			xAxis.setTextColor(color);
			xAxis.setTextSize(9.0f);
			xAxis.setAxisLineColor(color);
			xAxis.setAxisLineWidth(0.5f);
			xAxis.setLabelCount(14, true);
			xAxis.setSpaceMin(1000 * 86400.0f);// 24*3600 == 86400, 1 day
			xAxis.setSpaceMax(1000 * 43200.0f);//            43200, half a day
			YAxis axis = this.mChart.getAxis(YAxis.AxisDependency.LEFT);
			axis.setAxisMinimum(0.0f);
			axis.setLabelCount(3, true);
			axis.setTextColor(color);
			axis.enableGridDashedLine(Density.dp2px(this.context, 2.0f), Density.dp2px(this.context, 1.0f), 0.0f);
			axis.setGridLineWidth(0.5f);
			axis.setTextSize(9.0f);
			axis.setDrawZeroLine(false);
			axis.setAxisLineColor(color);
			axis.setAxisLineWidth(0.5f);
			axis.setPosition(YAxis.YAxisLabelPosition.INSIDE_CHART);
			axis.setSpaceTop(15.0f);
			axis.setYOffset(7.0f);
			axis.setValueFormatter(new DefaultAxisValueFormatter(0) {
				@Override public String getFormattedValue(float f, AxisBase axisBase) {
					return f == 0.0f ? "" : super.getFormattedValue(f, axisBase);
				}

				@Override public String getFormattedValue(float f) {
					return f == 0.0f ? "" : super.getFormattedValue(f);
				}
			});
			BarXAxisRenderer barXAxisRenderer = new BarXAxisRenderer(this.mChart.getViewPortHandler(), xAxis, this.mChart.getTransformer(YAxis.AxisDependency.LEFT));
			this.xAxisRenderer = barXAxisRenderer;
			this.mChart.setXAxisRenderer(barXAxisRenderer);
			this.mChart.setRendererLeftYAxis(new YAxisRenderer(this.mChart.getViewPortHandler(), axis, this.mChart.getTransformer(YAxis.AxisDependency.LEFT)) {
				@Override public void computeAxisValues(float f, float f2) {
					super.computeAxisValues(f, f2);
					float[] fArr = this.mAxis.mEntries;
					int i = this.mAxis.mEntryCount;
					if (i > 1) {
						int i2 = i - 1;
						this.mAxis.mEntries = new float[i2];
						System.arraycopy(fArr, 1, this.mAxis.mEntries, 0, i2);
						this.mAxis.mEntryCount = i2;
					}
				}
			});
			this.mChart.getAxisRight().setEnabled(false);
		}

		void setupUserData(User user) {
			setupChartData(user.getRecentHotList());
		}

		void setupChartData(String str) {
			this.mChartTitle.setText(R.string.mine_profile_hot_chart_title);
			List<MineHotItem> parseArray = TextUtils.isEmpty(str) ? Collections.emptyList() : JSON.parseArray(str, MineHotItem.class);
			int size = parseArray.size();

			ArrayList<BarEntry> arrayList = new ArrayList<>(size);
			for (int i = 0; i < size; i++) {
				MineHotItem mineHotItem = parseArray.get(i);
				long x = mineHotItem.getDate();
				arrayList.add(new BarEntry((float) x, mineHotItem.getHot()));
			}
			BarDataSet barDataSet = new BarDataSet(arrayList, "hot");
			barDataSet.setDrawValues(false);
			YAxis axis = this.mChart.getAxis(YAxis.AxisDependency.LEFT);
			float yMax = barDataSet.getYMax();
			if (yMax <= 20.0f) {
				axis.setAxisMaximum(20.0f);
			} else {
				axis.resetAxisMaximum();
			}
			int showChartNone = (yMax > 0.0f ? 1 : (yMax == 0.0f ? 0 : -1));
			this.mChartNone.setVisibility(showChartNone <= 0 ? View.VISIBLE : View.INVISIBLE);
			this.mChart.setAlpha(showChartNone <= 0 ? 0.4f : 1.0f);
			this.xAxisRenderer.setBarDataSet(barDataSet);
			BarData barData = new BarData(barDataSet);
			barData.setBarWidth(1000 * 28800.0f);//28800.0f, it has some relation with xAxis setSpaceMin setSpaceMax
			this.mChart.setData(barData);
			this.mChart.postInvalidate();
		}
	}

	private class DayAxisValueFormatter extends ValueFormatter {
		private String todayTag;
		private String[] weekTags;

		private DayAxisValueFormatter(Context context) {
			this.todayTag = context.getString(R.string.mine_profile_tag_today);
			this.weekTags = context.getResources().getStringArray(R.array.mine_week_tag);
		}

		@Override public String getFormattedValue(float f, AxisBase axisBase) {
			Calendar calendar = Calendar.getInstance();
			int i = calendar.get(6);
			calendar.setTimeInMillis((long) (f * 1000));//force type change
			if (i == calendar.get(6)) {
				return this.todayTag;
			}
			return this.weekTags[calendar.get(7) - 1];
		}

		@Override public String getFormattedValue(float f) {
			Calendar calendar = Calendar.getInstance();
			int i = calendar.get(Calendar.DAY_OF_YEAR);//6
			calendar.setTimeInMillis((long) (f));// * 1000));//force type change
			if (i == calendar.get(Calendar.DAY_OF_YEAR)) {
				return this.todayTag;
			}
			int index = calendar.get(Calendar.DAY_OF_WEEK);//7
			return this.weekTags[index - 1];
		}
	}
}